#!/usr/bin/env python
# -*- coding: utf-8 -*-
# datetime: 13/4/2023 下午9:34
# Author: name
# File: server_manage.py
# ide: PyCharm
# description: 服务器管理
import re
import time

import jmespath
import requests
from pywebio.output import *
from pywebio.pin import put_input, pin
from pywebio.session import eval_js

from backend.app.config import HOST
from commons.comms import close_pop, validate_ip, validate_port, is_not_empty

from frontend.menus import show_menus


def business_crud_data(action: str = None, item_id=None):
    if action == "save":
        server_name = is_not_empty(pin.server_name, "服务器名称")
        server_ip = validate_ip(pin.server_ip, "服务器地址")
        server_port = validate_port(pin.server_port, "端口号")
        server_username = is_not_empty(pin.server_username, "用户名")
        server_password = is_not_empty(pin.server_password, "密码")
        if server_name and server_ip and server_port and server_username and server_password:
            data = {
                "name": server_name,
                "address": server_ip,
                "port": server_port,
                "username": server_username,
                "password": server_password,
            }
            result = requests.post(HOST + "/server/add", json=data)
            print(result.json())
            toast(result.json().get("message"))

    elif action == "update":
        server_name = is_not_empty(pin.server_name, "服务器名称")
        server_ip = validate_ip(pin.server_ip, "服务器地址")
        server_port = validate_port(pin.server_port, "端口号")
        server_username = is_not_empty(pin.server_username, "用户名")
        server_password = is_not_empty(pin.server_password, "密码")
        if server_name and server_ip and server_port and server_username and server_password:
            data = {
                "name": server_name,
                "address": server_ip,
                "port": server_port,
                "username": server_username,
                "password": server_password,
            }
            result = requests.put(HOST + f"/server/{item_id}", json=data)
            toast(result.json().get("message"))
    elif action == "delete":
        result = requests.delete(HOST + f"/server/{item_id}")
        toast(result.json()["message"])
        time.sleep(1)
        eval_js("window.location.reload();")
    else:
        pass


def html_update_server(data):
    print(data)
    return popup('服务器编辑', [
        put_row([
            put_text("服务器名称"),
            put_text("*").style("color:red"),
            put_input("server_name", value=data[1]),
        ], size="15% 5% 70%"),
        put_row([
            put_text("服务器地址"),
            put_text("*").style("color:red"),
            put_input("server_ip", value=data[2]),
        ], size="15% 5% 70%"),
        put_row([
            put_text("端口号"),
            put_text("*").style("color:red"),
            put_input("server_port", value=data[3]),
        ], size="15% 5% 70%"),
        put_row([
            put_text("用户名"),
            put_text("*").style("color:red"),
            put_input("server_username", value=data[4]),
        ], size="15% 5% 70%"),
        put_row([
            put_text("密码"),
            put_text("*").style("color:red"),
            put_input("server_password", value=data[5]),
        ], size="15% 5% 70%"),
        put_row([
            None,
            put_button("提交", onclick=lambda: business_crud_data("update", data[0]), small=True),
            put_button('关闭', onclick=lambda: close_pop(), color="secondary", small=True)
        ], size="70% 15%"),

    ], size="large", closable=False)


def html_add_server():
    return popup('服务器新增', [
        put_row([
            put_text(f"服务器名称"),
            put_text("*").style("color:red"),
            put_input("server_name", placeholder="请输入服务器名称"),
        ], size="15% 5% 70%"),
        put_row([
            put_text("服务器地址"),
            put_text("*").style("color:red"),
            put_input("server_ip", placeholder="请输入服务器地址"),
        ], size="15% 5% 70%"),
        put_row([
            put_text("端口号"),
            put_text("*").style("color:red"),
            put_input("server_port", value=22, placeholder="请输入端口号"),
        ], size="15% 5% 70%"),
        put_row([
            put_text("用户名"),
            put_text("*").style("color:red"),
            put_input("server_username", placeholder="请输入用户名"),
        ], size="15% 5% 70%"),
        put_row([
            put_text("密码"),
            put_text("*").style("color:red"),
            put_input("server_password", placeholder="请输入密码"),
        ], size="15% 5% 70%"),
        put_row([
            None,
            put_button("提交", onclick=lambda: business_crud_data("save"), small=True),
            put_button('关闭', onclick=lambda: close_pop(), color="secondary", small=True)
        ], size="70% 15%"),

    ], size="large", closable=False)


def get_page_data(page: int = 1, size: int = 5, name: str = None):
    query_param = {
        "page": page,
        "size": size,
        "name": name if name else ""
    }
    response = requests.get(HOST + "/server/page", params=query_param)

    print(response.text)
    variable_json = response.json().get("results")
    total = response.json().get("total")
    search_key = response.json().get("search_key")
    data_list = []
    if variable_json:
        data_list = jmespath.search("[].values(@)", variable_json)
    for v in data_list:
        exec_code = f"""
v.append(
    put_row([
        put_button("编辑", onclick=lambda: html_update_server({v}),small=True),
        None,
        put_button("删除", onclick=lambda: business_crud_data('delete',{v[0]}),color="danger",small=True),
    ]
    )
)
"""
        exec(exec_code)
    print(data_list)
    return total, page, search_key, data_list


def business_pages_data(current_page=1, page_size=10, name=None):
    page_size = 10
    print(f"当前第{current_page}页")
    if current_page < 1:
        current_page = 1
        toast("当前第一页")
        return
    total, current_page, search_key, data_list = get_page_data(current_page, page_size, name)
    if total <= page_size:
        total_page = 1
    else:
        total_page = int(total / page_size) + 1
    if current_page > total_page:
        current_page = total_page
        toast("当前最后一页")
        return
    table_header = [
        put_html('<h4 style="width:40px">编号</h4>'),
        put_html('<h4 style="width:150px">服务器名称</h4>'),
        put_html('<h4 style="width:100px">服务器地址</h4>'),
        put_html('<h4 style="width:50px">端口号</h4>'),
        put_html('<h4 style="width:150px">用户名</h4>'),
        put_html('<h4 style="width:150px">密码</h4>'),
        put_html('<h4 style="width:150px">创建时间</h4>'),
        put_html('<h4 style="width:150px">更新时间</h4>'),
        put_html('<h4 style="width:100px">操作</h4>'),
    ]
    with use_scope("data_list", clear=True):
        put_tabs(
            [
                {
                    "title": "服务器列表",
                    "content": [
                        put_button("新增", onclick=lambda: html_add_server(), small=True),
                        put_row(
                            [
                                put_text("服务器名称: "),
                                put_input(name="server_search", placeholder="请输入服务器名称进行查询",
                                          value=search_key),
                                None,
                                put_button("搜索", onclick=lambda: business_pages_data(name=pin.server_search),
                                           small=True),
                                put_button("重置",
                                           onclick=lambda: business_pages_data(), small=True),
                            ], size="8% 50% 5% 6%"
                        ),
                        put_table(data_list, header=table_header),
                        put_row([
                            put_text(
                                f"      每页{page_size}条      当前第{current_page}/{total_page}页       总共{total}条"),
                            put_button("上一页",
                                       onclick=lambda: business_pages_data(current_page - 1, page_size), small=True),

                            put_button("下一页",
                                       onclick=lambda: business_pages_data(current_page + 1, page_size), small=True),

                        ], size="40% 6% 6%"
                        )

                    ]
                }
            ], scope="data_list"
        )


def html_show_server():
    """
    服务器管理
    """
    show_menus()
    business_pages_data()
